import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.DataGridEvent;
import mx.managers.CursorManager;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
//include the constant definition of the server endpoint URL
//include "billchildconfig.as";
//private var gateway:HTTPService = new HTTPService();
[Bindable]
public var dataArrs:ArrayCollection = new ArrayCollection();
private var orderColumns:Number;
private var fieldss:Object = { 'billNO':Number, 'DrugId':Number, 'Type':String, 'qty':Number};
private function initApps():void 
{
    gateway.url = ENDPOINT_URL;
    gateway.method = "POST";
    gateway.useProxy = false;
    gateway.resultFormat = "e4x";
//    dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_BEGINNING, editCellHandler);
 //   dataGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, editCellEnd);
    gateway.addEventListener(ResultEvent.RESULT, resultHandler);
    gateway.addEventListener(FaultEvent.FAULT, faultHandler);
    fill();
}
private function editCellHandlers(e:DataGridEvent):void
{
    if(e.dataField == "billNOCol")
    {
        e.preventDefault();
        return;
    }
}
private function filterResultss():void
{
    fill();
}
private function editCellEnds(e:DataGridEvent):void
{
    var dsRowIndex:int = e.rowIndex;
    var dsFieldName:String = e.dataField;
    var dsColumnIndex:Number = e.columnIndex;
    var vo:* = dataArrs[dsRowIndex];
//    var col:DataGridColumn = dataGrid.columns[dsColumnIndex];
//    var newvalue:String = dataGrid.itemEditorInstance[col.editorDataField];
   trace("a:" + dsRowIndex + ", " + dsFieldName + ", " + dsColumnIndex);
    var parameters:* =
    {
        "billNO": vo.billNOCol,        "DrugId": vo.DrugIdCol,        "Type": vo.TypeCol,        "qty": vo.qtyCol    }
//	parameters[dsFieldName.substr(0,dsFieldName.length-3)] = newvalue;
   doRequest("Update", parameters, saveItemHandler);    
}
private function saveItemHandlers(e:Object):void
{
    if (e.isError)
    {
        Alert.show("Error: " + e.data.error);
    }
    else
    {
    }     
}
private function setOrders(event:DataGridEvent):void 
{
    orderColumns = event.columnIndex;
 //   var col:DataGridColumn = dataGrid.columns[orderColumns];
 //   col.sortDescending = !col.sortDescending;
    event.preventDefault();
    fill();
}
public var i:int=0
public function insertItems():void {
for(i=0;i<=billdgarray.length-1;i++){
 var temp:String = billdgarray.getItemAt(i,0)[1];
 adddrug.selectedItem=temp;		
    var parameters:* =
    {
"method": "Insert",	"billNO": billno.text,	"DrugId": adddrug.selectedIndex,	"Type": type.selectedLabel,	"qty": billdgarray.getItemAt(i,0)[2] 
           };
    doRequest("Insert", parameters, insertItemsHandlers);
    Alert.show(""+i+adddrug.selectedIndex);
	}	
}
private function insertItemsHandlers(e:Object):void
{
    if (e.isError)
    {
        Alert.show("Error: " + e.data.error);
    }
    else
    {
//        goToView();
        fill();
    }     
}
private function fills():void 
{
     var desc:Boolean = false;
    var orderField:String = '';
    if(!isNaN(orderColumns))
    {
//        var col:DataGridColumn = dataGrid.columns[orderColumns];
 //       desc = col.sortDescending;
		//remove the 'Col' particle
 //       orderField = col.dataField.substr(0,col.dataField.length-3);
    }
//    dataGrid.enabled = false;
    CursorManager.setBusyCursor();
 /*    var parameters:* =
    {
        "orderField": orderField,
        "orderDirection": (desc) ? "DESC" : "ASC", 
        "filter": filterTxt.text
    }
    doRequest("FindAll", parameters, fillsHandler);
 */}
private function fillsHandlers(e:Object):void
{
    if (e.isError)
    {
        Alert.show("Error: " + e.data.error);
    } 
    else
    {
        dataArrs.removeAll();
        for each(var row:XML in e.data.row) 
        {
            var temp:* = {};
            for (var key:String in fieldss) 
            {
                temp[key + 'Col'] = row[key];
            }
            dataArrs.addItem(temp);
        }
        CursorManager.removeBusyCursor();
//        dataGrid.enabled = true;
    }    
}
private function deleteItems():void {
    
/*     if (dataGrids.selectedItem)
    {
        Alert.show("Are you sure you want to delete the selected record?",
        "Confirm Delete", 3, this, deleteClickHandler);
    }
 */    
}
private function deleteClickHandlers(event:CloseEvent):void
{
    if (event.detail == Alert.YES) 
    {
 //       var vo:* = dataGrids.selectedItem;

        var parameters:* =
        {
 //           "billNO": vo.billNOCol
        }
        doRequest("Delete", parameters, deleteHandler);

        setTimeout( function():void
        {
//            dataGrids.destroyItemEditor();
        },
        1);
    }
}
public function deleteHandlers(e:*):void
{
    if (e.isError)
    {
        Alert.show("Error: " + e.data.error);
    }
    else
    {
        var billNO:Number = parseInt(e.data.toString(), 10);
        for (var index:Number = 0; index < dataArrs.length; index++)
        {
            if (dataArrs[index].billNOCol == billNO)
            {
                dataArrs.removeItemAt(index);
                break;
            }
        }
    }     
}
public function deserializes(obj:*, e:*):*
{
    var toret:Object = {};
    toret.originalEvent = e;
   if (obj.data.elements("error").length() > 0)
    {
        toret.isError = true;
        toret.data = obj.data;
    }
    else
    {
        toret.isError = false;
        toret.metadata = obj.metadata;
        toret.data = obj.data;
    }
   return toret;
}
public function resultHandlers(e:ResultEvent):void
{
    var topass:* = deserializes(e.result, e);
    e.token.handler.call(null, topass);
}
public function faultHandlers(e:FaultEvent):void
{
	var errorMessage:String = "Connection error: " + e.fault.faultString; 
    if (e.fault.faultDetail) 
    { 
        errorMessage += "\n\nAdditional detail: " + e.fault.faultDetail; 
    } 
    Alert.show(errorMessage);
}
public function doRequests(method_name:String, parameters:Object, callback:Function):void
{
    // add the method to the parameters list
    parameters['method'] = method_name;

    gateway.request = parameters;

    var call:AsyncToken = gateway.send();
    call.request_params = gateway.request;

    call.handler = callback;
}/* 
public function goToUpdate():void
{
	applicationScreens.selectedChild = update;
}
public function goToView():void
{
    applicationScreens.selectedChild = view;
}
 */